import React from 'react';
import { WebView, Animated, ActivityIndicator, Image, FlatList, ScrollView, StyleSheet, Text, View, TouchableOpacity, Modal, TextInput, TouchableWithoutFeedback, DeviceEventEmitter } from 'react-native';

import ScrollableTabView, { BadgedTabBar, DefaultTabBar } from 'react-native-scrollable-tab-view'

const AnimatedFlatList = Animated.createAnimatedComponent(FlatList);

import ScreenUtils from '../Utils/ScreenUtils'
import ColorUtils from '../Utils/ColorUtils'
import RouterUtils from '../Utils/RouterUtils'
import ToastUtils from '../Utils/ToastUtils'
import PushUtil from '../Umeng/PushUtil'
import StorageUtils from '../Utils/StorageUtils'
import Constant from '../Constant/Constant'
import HttpUtils from '../Utils/HttpUtils'

export default class PageLddbList extends React.Component
{
    static navigationOptions = ({navigation}) => ({
        gesturesEnabled: false,//是否支持滑动返回收拾，iOS默认支持，安卓默认关闭
        headerTitle: '领导督办',
        headerStyle: {
            backgroundColor: ColorUtils.blue,
            height: ScreenUtils.statusBarHeight,
        },
        headerRight: (<Text></Text>),
        headerTintColor: ColorUtils.white,
        headerTitleStyle: {
            fontSize: ScreenUtils.Font_18,
            color: ColorUtils.white,
            fontWeight: 'normal',
            flex: 1,
            alignSelf: 'center',
            textAlign: 'center',
        }
    });

    constructor(props)
    {
        super(props);
        this.state = {
            //tab1
            pageIndexNeed: 1,
            onRefreshingNeed: true,
            onLoadMoreNeed: false,
            loadMoreCountNeed: 0,
            dataSourceNeed: [],
            isNoDataNeed: false,
            //tab2
            pageIndexHistory: 1,
            onRefreshingHistory: false,
            onLoadMoreHistory: false,
            loadMoreCountHistory: 0,
            dataSourceHistory: [],
            isNoDataHistory: false,
        };
    }

    componentDidMount()
    {
        RouterUtils.pushRouter('PageLddbList', this.props.navigation.state.key);
        this.listener1 = DeviceEventEmitter.addListener('lddbOnRefresh', (events) => this.lddbOnRefresh());
        this.lddbOnRefresh();
    }

    componentWillUnmount()
    {
        RouterUtils.popRouter('PageLddbList', this.props.navigation.state.key);
        this.listener1.remove();
    }

    onChangeTabs(obj)
    {
    }

    lddbOnRefresh()
    {
        this.getNeedList();//获取待督办列表
        this.getHistoryList();//获取已督办列表
    }

    getHistoryList()
    {
        try
        {
            var that = this;
            StorageUtils.get('session').then((session) =>
            {
                if (session != '' && session != null)
                {
                    HttpUtils.getJson(Constant.lddbAlerdyList + '?current=' + that.state.pageIndexHistory + '&size=20', session, function (resultcode, data)
                    {
                        if (that.state.pageIndexNeed == 1)
                        {
                            that.setState({
                                onRefreshingHistory: false,
                                onLoadMoreHistory: data.records.length > 0,
                                dataSourceHistory: data.records,
                                loadMoreCountHistory: data.records.length,
                                isNoDataHistory: data.records.length == 0
                            });
                        } else
                        {
                            that.setState({
                                onRefreshingHistory: false,
                                onLoadMoreHistory: data.records.length > 0,
                                dataSourceHistory: that.state.dataSourceHistory.concat(data.records),
                                loadMoreCountHistory: data.records.length,
                                isNoDataHistory: false
                            });
                        }
                    }, function (resultcode, reason)
                    {
                        ToastUtils.toastShortBottom('错误码:' + resultcode + ',错误原因:' + reason);
                    });
                }
            });
        }
        catch (error)
        {
            ToastUtils.toastShortBottom(error);
        }
    }

    getNeedList()
    {
        try
        {
            var that = this;
            StorageUtils.get('session').then((session) =>
            {
                if (session != '' && session != null)
                {
                    HttpUtils.getJson(Constant.lddbNeedList + '?current=' + that.state.pageIndexNeed + '&size=20', session, function (resultcode, data)
                    {
                        if (that.state.pageIndexNeed == 1)
                        {
                            that.setState({
                                onRefreshingNeed: false,
                                onLoadMoreNeed: data.records.length > 0,
                                dataSourceNeed: data.records,
                                loadMoreCountNeed: data.records.length,
                                isNoDataNeed: data.records.length == 0
                            });
                        } else
                        {
                            that.setState({
                                onRefreshingNeed: false,
                                onLoadMoreNeed: data.records.length > 0,
                                dataSourceNeed: that.state.dataSourceNeed.concat(data.records),
                                loadMoreCountNeed: data.records.length,
                                isNoDataNeed: false
                            });
                        }
                    }, function (resultcode, reason)
                    {
                        ToastUtils.toastShortBottom('错误码:' + resultcode + ',错误原因:' + reason);
                    });
                }
            });
        }
        catch (error)
        {
            ToastUtils.toastShortBottom(error);
        }
    }

    jumpDetail(status, id, processInstanceId)
    {
        this.props.navigation.navigate('PageLddbDetail', {'status': status, 'id': id, 'processInstanceId': processInstanceId});
    }

    renderFooterNeed()
    {
        if (this.state.isNoDataNeed)
        {
            return (
                <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
                    <Image resizeMode={Image.resizeMode.stretch} style={{marginTop: 80, width: 152, height: 120}} source={require('../img/list_nodata.png')}/>
                    <Text style={{fontSize: ScreenUtils.Font_14, color: '#7EA0BF', fontWeight: 'bold', marginTop: 8}}>暂无数据</Text>
                </View>
            );
        }
        if (this.state.loadMoreCountNeed < 20)
        {
            this.state.onLoadMoreNeed = false;
            return null;
        }
        else
        {
            return (
                <View style={{paddingBottom: 2, flexDirection: 'row', justifyContent: 'center', alignItems: 'center'}}>
                    <ActivityIndicator style={{width: 25, height: 25,}} color='#264A70'/>
                    <Text style={{marginLeft: 4, fontSize: ScreenUtils.Font_10}}>执行中...</Text>
                </View>
            );
        }
    }

    onRefreshNeed()
    {
        console.log('pull refresh Need..')
        this.state.pageIndexNeed = 1;
        this.getNeedList();
    }

    onLoadMoreNeed()
    {
        console.log('pull load Log..')
        if (!this.state.onLoadMoreNeed) return null;
        this.state.pageIndexNeed = this.state.pageIndexNeed + 1;
        this.getNeedList();
    }

    renderNeedMsgItem({item})
    {
        return (
            <TouchableOpacity key={item.id} activeOpacity={0.8} onPress={() => this.jumpDetail('未上报', item.id, item.processInstanceId)} style={{paddingTop: 16, paddingLeft: 16, paddingRight: 16}}>
                <View style={{flexDirection: 'row'}}>
                    <View style={{height: '100%', backgroundColor: ColorUtils.blue, width: 3}}/>
                    <View style={{marginLeft: 4, flex: 1, flexDirection: 'column', justifyContent: 'center', marginLeft: 8}}>
                        <View style={{flexDirection: 'row', alignItems: 'center'}}>
                            <Text style={{fontSize: ScreenUtils.Font_14, color: ColorUtils.light_gray}}>案件编号:</Text>
                            <Text style={{marginLeft: 8, fontSize: ScreenUtils.Font_14, color: ColorUtils.black}}>{item.caseNo == "" ? '无' : item.caseNo}</Text>
                        </View>
                        <View style={{marginTop: 8, flexDirection: 'row', alignItems: 'center'}}>
                            <Text style={{fontSize: ScreenUtils.Font_14, color: ColorUtils.light_gray}}>案件类型:</Text>
                            <Text style={{marginLeft: 8, fontSize: ScreenUtils.Font_14, color: ColorUtils.black}}>{item.categoryName}</Text>
                        </View>
                        <View style={{marginTop: 8, flexDirection: 'row', alignItems: 'center'}}>
                            <Text style={{fontSize: ScreenUtils.Font_14, color: ColorUtils.light_gray}}>案件大类:</Text>
                            <Text style={{marginLeft: 8, fontSize: ScreenUtils.Font_14, color: ColorUtils.black}}>{item.categoryOneName}</Text>
                        </View>
                        <View style={{marginTop: 8, flexDirection: 'row', alignItems: 'center'}}>
                            <Text style={{fontSize: ScreenUtils.Font_14, color: ColorUtils.light_gray}}>案件小类:</Text>
                            <Text style={{marginLeft: 8, fontSize: ScreenUtils.Font_14, color: ColorUtils.black}}>{item.categoryTwoName}</Text>
                        </View>
                    </View>
                    <View style={{height: 26, justifyContent: 'center', padding: 6, borderRadius: 4, backgroundColor: '#FFD1D5'}}>
                        <Text style={{color: '#FF192F', fontSize: ScreenUtils.Font_10}}>
                            待督办
                        </Text>
                    </View>
                </View>
                <View style={{marginTop: 16, height: 1, borderColor: ColorUtils.line, borderBottomWidth: 1}}/>
            </TouchableOpacity>
        );
    }

    renderFooterHistory()
    {
        if (this.state.isNoDataHistory)
        {
            return (
                <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
                    <Image resizeMode={Image.resizeMode.stretch} style={{marginTop: 80, width: 152, height: 120}} source={require('../img/list_nodata.png')}/>
                    <Text style={{fontSize: ScreenUtils.Font_14, color: '#7EA0BF', fontWeight: 'bold', marginTop: 8}}>暂无数据</Text>
                </View>
            );
        }
        if (this.state.loadMoreCountHistory < 20)
        {
            this.state.onLoadMoreHistory = false;
            return null;
        } else
        {
            return (
                <View style={{paddingBottom: 2, flexDirection: 'row', justifyContent: 'center', alignItems: 'center'}}>
                    <ActivityIndicator style={{width: 25, height: 25,}} color='#2C98F2'/>
                    <Text style={{marginLeft: 4, fontSize: ScreenUtils.Font_10}}>执行中...</Text>
                </View>
            );
        }
    }

    onRefreshHistory()
    {
        console.log('pull refresh History..')
        this.state.pageIndexHistory = 1;
        this.getHistoryList();
    }

    onLoadMoreHistory()
    {
        console.log('pull load History..')
        if (!this.state.onLoadMoreHistory) return null;
        this.state.pageIndexHistory = this.state.pageIndexHistory + 1;
        this.getHistoryList();
    }

    renderHistoryItemView({item})
    {
        return (
            <TouchableOpacity key={item.id} activeOpacity={0.8} onPress={() => this.jumpDetail('已督办', item.id, item.processInstanceId)} style={{paddingTop: 16, paddingLeft: 16, paddingRight: 16}}>
                <View style={{flexDirection: 'row'}}>
                    <View style={{height: '100%', backgroundColor: ColorUtils.blue, width: 3}}/>
                    <View style={{marginLeft: 4, flex: 1, flexDirection: 'column', justifyContent: 'center', marginLeft: 8}}>
                        <View style={{flexDirection: 'row', alignItems: 'center'}}>
                            <Text style={{fontSize: ScreenUtils.Font_14, color: ColorUtils.light_gray}}>案件编号:</Text>
                            <Text style={{marginLeft: 8, fontSize: ScreenUtils.Font_14, color: ColorUtils.black}}>{item.caseNo == "" ? '无' : item.caseNo}</Text>
                        </View>
                        <View style={{marginTop: 8, flexDirection: 'row', alignItems: 'center'}}>
                            <Text style={{fontSize: ScreenUtils.Font_14, color: ColorUtils.light_gray}}>案件类型:</Text>
                            <Text style={{marginLeft: 8, fontSize: ScreenUtils.Font_14, color: ColorUtils.black}}>{item.categoryName}</Text>
                        </View>
                        <View style={{marginTop: 8, flexDirection: 'row', alignItems: 'center'}}>
                            <Text style={{fontSize: ScreenUtils.Font_14, color: ColorUtils.light_gray}}>案件大类:</Text>
                            <Text style={{marginLeft: 8, fontSize: ScreenUtils.Font_14, color: ColorUtils.black}}>{item.categoryOneName}</Text>
                        </View>
                        <View style={{marginTop: 8, flexDirection: 'row', alignItems: 'center'}}>
                            <Text style={{fontSize: ScreenUtils.Font_14, color: ColorUtils.light_gray}}>案件小类:</Text>
                            <Text style={{marginLeft: 8, fontSize: ScreenUtils.Font_14, color: ColorUtils.black}}>{item.categoryTwoName}</Text>
                        </View>
                    </View>
                    <View style={{height: 26, justifyContent: 'center', padding: 6, borderRadius: 4, backgroundColor: '#D6EAFF'}}>
                        <Text style={{color: '#3197FF', fontSize: ScreenUtils.Font_10}}>
                            已督办
                        </Text>
                    </View>
                </View>
                <View style={{marginTop: 16, height: 1, borderColor: ColorUtils.line, borderBottomWidth: 1}}/>
            </TouchableOpacity>
        );
    }

    render()
    {
        return (
            <View style={styles.container}>
                <ScrollableTabView
                    locked={true}
                    renderTabBar={() => <DefaultTabBar style={{flexDirection: 'row', borderBottomWidth: 0, paddingBottom: 3, height: 45}}/>}
                    onChangeTab={this.onChangeTabs.bind(this)}
                    tabBarUnderlineStyle={styles.tabBarUnderlineStyle}
                    tabBarTextStyle={styles.tabBarTextStyle}
                    tabBarBackgroundColor={ColorUtils.white}
                    tabBarInactiveTextColor={ColorUtils.black}
                    tabBarActiveTextColor={ColorUtils.blue}>
                    <AnimatedFlatList
                        tabLabel='待督办'
                        data={this.state.dataSourceNeed}
                        keyExtractor={item => item.id}
                        renderItem={this.renderNeedMsgItem.bind(this)}
                        ListFooterComponent={this.renderFooterNeed.bind(this)}
                        refreshing={this.state.onRefreshingNeed}
                        onRefresh={this.onRefreshNeed.bind(this)}
                        onEndReached={this.onLoadMoreNeed.bind(this)}
                        onEndReachedThreshold={1}
                    />
                    <AnimatedFlatList
                        tabLabel='已督办'
                        data={this.state.dataSourceHistory}
                        keyExtractor={item => item.id}
                        renderItem={this.renderHistoryItemView.bind(this)}
                        ListFooterComponent={this.renderFooterHistory.bind(this)}
                        refreshing={this.state.onRefreshingHistory}
                        onRefresh={this.onRefreshHistory.bind(this)}
                        onEndReached={this.onLoadMoreHistory.bind(this)}
                        onEndReachedThreshold={1}
                    />
                </ScrollableTabView>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: ColorUtils.white,
    },
    tabBarUnderlineStyle: {
        height: 2,
        minWidth: Math.floor(ScreenUtils.width * 0.8 / 8),
        backgroundColor: ColorUtils.blue,
    },
    tabBarTextStyle: {
        fontSize: ScreenUtils.Font_14,
        fontWeight: 'normal'
    }
});


